/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.socket.server;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.bambamboo.socket.server.grizzly.GrizzlyTCPServer;
import com.bambamboo.socket.server.mina.MinaTCPServer;
import com.bambamboo.socket.server.mina.SerialServer;
import com.bambamboo.socket.server.netty.NettyTCPServer;

/**
 * The main entry to startup TCP server
 * 
 * @author Nick.Tan
 */
public class Server {

	private static Log logger = LogFactory.getLog(Server.class);
	private ApplicationContext appCtx;

	public static void main(String[] args) {
		Server server = new Server();
		server.initialize(args);
		try {
			server.startup();
		}
		catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public void initialize(String[] args) {
		appCtx = new FileSystemXmlApplicationContext("./config/applicationContext.xml");
	}

	public void startup() throws Exception {
		Map<String, ServerConfigurationBean> beans = appCtx.getBeansOfType(ServerConfigurationBean.class);
		logger.info("================== starting server ... ==================");
		for (Map.Entry<String, ServerConfigurationBean> entry : beans.entrySet()) {
			ServerConfigurationBean bean = entry.getValue();
			if (bean.isEnable() == false) {
				logger.info(">>> server configuration disabled: " + bean);
				continue;
			}

			AbstractIOServer svr = null;
			String name = bean.getImplementor();
			if (name == null || name.trim().length() == 0) {
				name = "netty"; // default as "netty"
			}
			if ("netty".equalsIgnoreCase(name)) {
				svr = new NettyTCPServer();
			}
			else if ("mina".equalsIgnoreCase(name)) {
				svr = new MinaTCPServer();
			}
			else if ("grizzly".equalsIgnoreCase(name)) {
				svr = new GrizzlyTCPServer();
			}
			else if ("mina-serial".equalsIgnoreCase(name)) {
				svr = new SerialServer();
			}

			svr.setServerConfigurationBean(bean);
			svr.startup();
		}
		logger.info("================== server started ==================");
	}
}
